﻿using System;
using System.Linq;
using Infrastructure.Interfaces;
using Infrastructure.ViewModel;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;

namespace Infrastructure.Module
{
    public abstract class ModuleBase : IModule
    {
        #region Member variables
        private IUnityContainer unityContainer;
        #endregion

        #region Initialize
        public abstract void Initialize();
        #endregion

        #region Unity container
        [Dependency]
        public IUnityContainer UnityContainer
        {
            get { return this.unityContainer; }
            set
            {
                this.unityContainer = value;
                if (unityContainer != null)
                {
                    foreach (Type type in this.GetType().Assembly.GetTypes().Where(
                        t => t.GetInterfaces().Contains(typeof(IView))))
                        this.unityContainer.RegisterType(typeof(object), type, type.Name);
                }
                
                this.RegionManager = this.unityContainer.Resolve<IRegionManager>();
            }
        }
        #endregion

        #region Region manager
        public IRegionManager RegionManager { get; set; }
        #endregion

        #region Register view model with view
        protected void RegisterViewModelWithView<TViewType, TViewModelType>()
            where TViewType : IView
            where TViewModelType : ViewModelBase
        {
            //TODO: Implement class derived from RegionNavigationContentLoader so we can use FullName instead of Name.
            this.UnityContainer.RegisterType<ViewModelBase, TViewModelType>(typeof(TViewType).Name);
        }
        #endregion

        #region Register singleton view model with view
        protected void RegisterSingletonViewModelWithView<TViewType, TViewModelType>()
            where TViewType : IView
            where TViewModelType : ViewModelBase
        {
            //TODO: Implement class derived from RegionNavigationContentLoader so we can use FullName instead of Name.
            var viewModel = this.UnityContainer.Resolve<TViewModelType>();

            this.UnityContainer.RegisterInstance<ViewModelBase>(typeof(TViewType).Name, viewModel, new ContainerControlledLifetimeManager());
        }
        #endregion
    }
}
